﻿using System.Data;
using System.Reflection;
using Elsa.Workflows.Management.Entities;
using T.ServiceComponent.DAC.Service;
using WorkflowDefinition = T.FAS.Runtime.MF.Entity.ElsaEntity.WorkflowDefinition;

namespace T.FAS.Runtime.MF.Dao.Dao
{
    public class WorkflowDefinitionDao : DaoService<WorkflowDefinition>
    {
        public override string TableName => "WorkflowInstances";
        public override string IDColumnName => "Id";
        public override string DBName => "TFASMF";

        public WorkflowDefinition GetDefById(string defId,int? version)
        {
            string sql = @$"SELECT ""Id"", ""DefinitionId"", ""Name"", ""Description"",
                        ""ToolVersion"", ""ProviderName"", ""MaterializerName"", ""MaterializerContext"", 
                        ""StringData"", ""BinaryData"", ""IsReadonly"", ""Data"", ""UsableAsActivity"", 
                        ""CreatedAt"", ""Version"", ""IsLatest"", ""IsPublished"", ""IsSystem"", 
                        ""TenantId""
                        FROM ""Elsa"".""WorkflowDefinitions"" Where ""DefinitionId""='{defId}'";

            if (version.HasValue)
            {
                sql += @$" AND ""Version""={version.Value}";
            }
            var dataSet = this.DB.ExecuteDataSet(sql);

            if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count>0)
            {
                var dataRow = dataSet.Tables[0].Rows[0];

                var def = ConvertToObject(base.Columns, dataRow);
                def.CreatedAt = def.CreatedAt.AddHours(8);
              
                return def;
            }
            return null;
        }
        public override WorkflowDefinition ConvertToObject(Dictionary<string, PropertyInfo> columns, DataRow row)
        {
            var myCol = new Dictionary<string, PropertyInfo>(base.Columns);

            var data = base.ConvertToObject(myCol, row);

            return data;
        }

    }
}

